package com.lsy.weizhi2.fragment;

import android.app.Activity;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.model.GlideUrl;
import com.bumptech.glide.load.model.LazyHeaders;
import com.google.gson.Gson;
import com.lsy.weizhi2.JsonObject.NoteList;
import com.lsy.weizhi2.R;
import com.lsy.weizhi2.activity.ClassifyActivity;
import com.lsy.weizhi2.activity.LoginActivty;
import com.lsy.weizhi2.adapter.FragmentAdapter;
import com.lsy.weizhi2.config.Constants;
import com.lsy.weizhi2.config.MyHeight;
import com.lsy.weizhi2.config.MyInfo;
import com.lsy.weizhi2.customview.GlideCircleTransform;
import com.lsy.weizhi2.customview.MyVerticalViewPager;
import com.lsy.weizhi2.customview.SearchView;
import com.lsy.weizhi2.myutils.AddressCall;
import com.lsy.weizhi2.myutils.HomeFragmentCall;
import com.lsy.weizhi2.myutils.SearchCall;
import com.lsy.weizhi2.popupwindow.SelectPopup;
import com.lsy.weizhi2.utils.MyMethod;
import com.lsy.weizhi2.utils.MyOkHttpUtils;
import com.lsy.weizhi2.utils.TextHelper;


import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by 嗨哟 on 2017/3/13.
 */
public class HomeFragment extends Fragment {
    private Context context;
    private MyVerticalViewPager home_frag_mvvp;
    private HomeFragmentUp homeFragmentUp;
    private HomeFragmentDown homeFragmentDown;
    private List<Fragment> list_f;
    private Gson gson;
    private FragmentManager fragmentManager;
    private FragmentAdapter fragmentAdapter;
    public static SearchView home_search;
    private ImageView home_touxiang;
    private LinearLayout search_ll;
    private int search_top, search_left;
    public static int index;
    private int xx;
    private HomeFragmentCall homeFragmentCall;
    private Handler handler = new Handler(Looper.getMainLooper());

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.home_fragment, container, false);
        home_frag_mvvp = (MyVerticalViewPager) view.findViewById(R.id.home_frag_mvvp);
        home_search = (SearchView) view.findViewById(R.id.home_search);
        home_touxiang = (ImageView) view.findViewById(R.id.home_touxiang);
        search_ll = (LinearLayout) view.findViewById(R.id.search_ll);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable final Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        context = getActivity();
        gson = new Gson();
        homeFragmentUp = new HomeFragmentUp();
        homeFragmentDown = new HomeFragmentDown();
        list_f = new ArrayList<>();
        list_f.add(homeFragmentUp);
        list_f.add(homeFragmentDown);
        fragmentManager = getChildFragmentManager();
        fragmentAdapter = new FragmentAdapter(fragmentManager, list_f);
        home_frag_mvvp.setAdapter(fragmentAdapter);
        home_frag_mvvp.setCurrentItem(index);
        home_search.setSearchCall(new SearchCall() {
            @Override
            public void Search_S(View view, String address, String content) {
                //往服务器发送地址和搜索内容
                MyMethod.toActivity(context, ClassifyActivity.class);
                MyMethod.showToast(context, "address=" + address + "\n" + "content=" + content);
            }

            @Override
            public void Search_Text(View view) {
                SelectPopup popup = new SelectPopup(new AddressCall() {
                    @Override
                    public void Select(String p, String c, String d, String f) {
                        switch (f) {
                            case "address":
                                home_search.setHome_addr(p);
                                break;
                        }
                    }
                });
                popup.setShowCount(1);
                popup.setFlag("address");
                String[] strs = TextHelper.citys.get("湖北");
                popup.setStrs(strs);
                popup.init(context);
            }
        });

        home_frag_mvvp.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            public int state;

            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                if (state != 0) {
                    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(search_ll.getLayoutParams());
                    int x = (int) (positionOffsetPixels * positionOffset);
                    params.leftMargin = search_left;
                    params.topMargin = search_top - x;
                    search_ll.setLayoutParams(params);
                }

            }

            @Override
            public void onPageSelected(int position) {
                if (position == 1) {
                    home_search.setVisibility(View.INVISIBLE);
                    home_touxiang.setVisibility(View.INVISIBLE);
                } else {
                    home_search.setVisibility(View.VISIBLE);
                    home_touxiang.setVisibility(View.VISIBLE);
                    getListNotes();
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                this.state = state;
                Log.i("HomeFrag", "state===" + state);
            }
        });
    }

    private void getListNotes() {
        Log.i("HomeFragmentUp", "token==" + MyInfo.Token);
        Map<String, String> map = new HashMap<>();
        //map.put("orderLevel", "2");//滚动播放传2
        map.put("pageNo", "1");
        map.put("pageSize", "20");
        MyOkHttpUtils.getInstance(context).doGet(Constants.ORDERLIST, map)
                .excute(new MyOkHttpUtils.OKCallBack() {
                    @Override
                    public void onFailure(String message) {

                    }

                    @Override
                    public void onResponse(String message) {
                        Log.i("HomeFragmentUp", "message=note=" + message);
                        if (message != null) {
                            try {
                                JSONObject jsonObject=new JSONObject(message);
                                boolean result = jsonObject.getBoolean("result");
                                if(result){
                                    NoteList noteList = gson.fromJson(message, NoteList.class);
                                    homeFragmentUp.getFragmentUpAdapter().UpData(3, noteList.getList());
                                }else{
                                    String msg=jsonObject.getString("message");
                                    if(msg.equals("错误的认证Token")){
                                        MyMethod.ShowDialogLogin(context,LoginActivty.class);
                                    }else if(msg.equals("用户不存在")){
                                        MyMethod.toActivity(context,LoginActivty.class);
                                        ((Activity)context).finish();
                                    }

                                }
                            } catch (Exception e) {
                                Log.i("HomeFragmentUp", "message=错误=note=" + e.getMessage());
                            }
                        }
                    }
                });
        Map<String, String> map1 = new HashMap<>();
        map1.put("orderLevel", "3");//悬赏传3
        map1.put("pageNo", "1");
        map1.put("pageSize", "20");
        MyOkHttpUtils.getInstance(context).doGet(Constants.ORDERLIST, map1)
                .excute(new MyOkHttpUtils.OKCallBack() {
                    @Override
                    public void onFailure(String message) {

                    }

                    @Override
                    public void onResponse(String message) {
                        if (message != null) {
                            try {
                                NoteList noteList = gson.fromJson(message, NoteList.class);
                                homeFragmentUp.getFragmentUpAdapter().UpData(1, noteList.getList());
                            } catch (Exception e) {
                                Log.i("HomeFragmentUp", "message=错误=note=" + message);
                            }
                        }
                    }
                });
    }

    @Override
    public void onStart() {
        super.onStart();
    }

    int left, height;

    @Override
    public void onResume() {
        super.onResume();
        Log.i("ParentView","home_frag_mvvp=homef="+home_frag_mvvp);
        xx = 0;
        Log.i("HomeFragment", "onResume");
        ViewTreeObserver vto = search_ll.getViewTreeObserver();
        vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                left = search_ll.getLeft();
                if (xx < 1) {
                    xx++;
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(search_ll.getLayoutParams());
                            params.topMargin = MyHeight.ACTIONBAR;
                            params.leftMargin = left;
                            search_left = left;
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                                search_top = MyHeight.ACTIONBAR;
                                params.topMargin = MyHeight.ACTIONBAR;
                            } else {
                                search_top = 0;
                                params.topMargin = 0;
                            }
                            Log.i("HomeFragment", "params.topMargin==" + params.topMargin);
                            search_ll.setLayoutParams(params);
                        }
                    });
                }

            }
        });
        Glide.with(context).load(new GlideUrl(Constants.DOWN_USER_PICTURE+MyInfo.Avatar,new LazyHeaders.Builder().addHeader("WZ-AUTH-TOKEN",MyInfo.Token).addHeader("WZ-AUTH-ID",MyInfo.User_Id+"").build()))
                .transform(new GlideCircleTransform(context)).error(R.mipmap.default_head).into(home_touxiang);
        getListNotes();
    }

    @Override
    public void onPause() {
        super.onPause();
        Log.i("HomeFragment", "onPause");
        xx = 0;
    }

    @Override
    public void onStop() {
        super.onStop();
        Log.i("HomeFragment", "onStop");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i("HomeFragment", "onDestroy");
    }

    public void setHomeFragmentCall(HomeFragmentCall homeFragmentCall) {
        this.homeFragmentCall = homeFragmentCall;
    }
}
